<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAddLine"
          v-hasPermi="['IssueLine:IssueLine:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="singleLine"
          @click="handleUpdateLine"
          v-hasPermi="['IssueLine:IssueLine:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multipleLine"
          @click="handleDeleteLine"
          v-hasPermi="['IssueLine:IssueLine:remove']"
        >删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loadingLine" :data="IssueLineList" @selection-change="handleSelectionChangeLine">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品物料编码" align="center" prop="itemCode" />
      <el-table-column label="产品物料名称" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="领料数量" align="center" prop="quantityIssued" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdateLine(scope.row)" v-hasPermi="['IssueLine:IssueLine:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDeleteLine(scope.row)" v-hasPermi="['IssueLine:IssueLine:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="totalLine>0"
      :total="totalLine"
      v-model:page="queryParamsLine.pageNum"
      v-model:limit="queryParamsLine.pageSize"
      @pagination="getListLine"
    />

    <!-- 添加或修改生产领料单行对话框 -->
      <el-dialog v-model="open3"  :title="titletui" width="900px" @close="handleDialogClose3">
        <el-row :gutter="15">
          <el-form ref="IssueLineRef" :model="formtui" :rules="rulestui" size="default" label-width="120px">
            <el-col :span="24">
              <el-row gutter="15">
                <el-col :span="8">
                  <el-form-item label="物料编码" prop="itemCode">
                    <el-input v-model="formtui.itemCode" type="text" placeholder="请输入物料编码" clearable disabled
                      :style="{width: '100%'}"></el-input>
                    <el-icon @click="kaii1" style="border: 1px solid #DCDFE6;width: 30px;height: 30px;background-color: #F5F7FA;cursor: pointer;position: relative;left:155px;top:-31px"><Search /></el-icon>

                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="物料名称" prop="itemName">
                    <el-input v-model="formtui.itemName" type="text" placeholder="请输入物料名称" clearable disabled
                      :style="{width: '100%'}"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="单位" prop="unitOfMeasure">
                    <el-input v-model="formtui.unitOfMeasure" type="text" placeholder="请输入单位" clearable disabled
                      :style="{width: '100%'}"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
            
            <el-col :span="20">
              <el-form-item label="规格型号" prop="specification">
                <el-input v-model="formtui.specification" type="text" placeholder="请输入规格型号" clearable disabled
                  :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-row gutter="15">
                <el-col :span="11">
                  <el-form-item label="批次号" prop="batchCode" >
                    <el-input v-model="formtui.batchCode" type="text"  clearable disabled
                      :style="{width: '100%'}"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="领料数量" prop="quantityIssued">
                    <el-input v-model="formtui.quantityIssued" type="text" placeholder="请输入领料数量" clearable
                      :style="{width: '100%'}"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-form>
        </el-row>
        <template #footer>
          <el-button @click="cancelLine">取消</el-button>
          <el-button type="primary" @click="submitFormLine">确定</el-button>
        </template>
      </el-dialog>
      <!-- 物料选择 -->
       <el-dialog v-model="open4" width="1200px"   @close="handleDialogClose1">
          <el-container>
            <el-aside width="200px" style="background-color: white;">
            <el-table
              style="border: none;"
              v-if="refreshTable"
              :data="type1List"
              row-key="itemTypeId"
              :default-expand-all="isExpandAll"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
              @row-click="handleCategoryClick" > <!-- 新增：点击分类行触发查询 -->
              <el-table-column  align="center" prop="itemTypeName" />
            </el-table>
              </el-aside>
              <el-main>
            <el-form :model="queryParams2" ref="queryRef" :inline="true" v-show="showSearch2" label-width="68px">
              <el-form-item label="物料编码" prop="itemCode">
                <el-input
                  v-model="queryParams2.itemCode"
                  placeholder="请输入产品物料编码"
                  clearable
                  @keyup.enter="handleQuery2"
                />
              </el-form-item>
              <el-form-item label="物料名称" prop="itemName">
                <el-input
                  v-model="queryParams2.itemName"
                  placeholder="请输入产品物料名称"
                  clearable
                  @keyup.enter="handleQuery2"
                />
              </el-form-item>
              <el-form-item label="批次号" prop="batchCode">
                <el-input
                  v-model="queryParams2.batchCode"
                  placeholder="请输入批次号"
                  clearable
                  
                  @keyup.enter="handleQuery2"
                />
              </el-form-item>
              <el-form-item label="仓库" prop="warehouseName">
                <el-input
                  v-model="queryParams2.warehouseName"
                  placeholder="请输入仓库"
                  clearable
                  @keyup.enter="handleQuery2"
                />
              </el-form-item>
              <el-form-item label="库区" prop="locationName">
                <el-input
                  v-model="queryParams2.locationName"
                  placeholder="请输入库区"
                  clearable
                  @keyup.enter="handleQuery2"
                />
              </el-form-item>
              <el-form-item label="库位" prop="areaName">
                <el-input
                  v-model="queryParams2.areaName"
                  placeholder="请输入库位"
                  clearable
                  @keyup.enter="handleQuery2"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery2">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery2">重置</el-button>
              </el-form-item>
            </el-form>

          <el-table v-loading="loading2" ref="userTableRef" :data="userList1" 
          @row-click="handleTableRowClick" :highlight-current-row="true" @select="handleRadioChange2">
             <el-table-column type="radio" width="50" />
            <el-table-column label="物料编码" align="center" prop="itemCode" />
            <el-table-column label="物料名称" align="center" prop="itemName" />
            <el-table-column label="规格型号" align="center" prop="specification" />
            <el-table-column label="在库数量" align="center" prop="quantityOnhand" />
            <el-table-column label="单位" align="center" prop="unitOfMeasure" />
            <el-table-column label="批次号" align="center" prop="batchCode" />
            <el-table-column label="仓库" align="center" prop="warehouseName" />
            <el-table-column label="库区" align="center" prop="locationName" />
            <el-table-column label="库位" align="center" prop="areaName" />
            <el-table-column label="入库时间" align="center" prop="recptDate" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.recptDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            
          </el-table>
          
          <pagination
            v-show="total2>0"
            :total="total2"
            v-model:page="queryParams2.pageNum"
            v-model:limit="queryParams2.pageSize"
            @pagination="getList2"
          />
        </el-main>
        </el-container>
        <el-button style="margin-left: 950px;" type="primary" @click="confirmSelectedItem2">确 认</el-button>
        <el-button @click="cancel1">关 闭</el-button>
        </el-dialog>
  </div>
</template>

<script setup name="IssueLine">
//------------------------------生产领料单行表数据渲染开始
import { listIssueLine, getIssueLine, delIssueLine, addIssueLine, updateIssueLine } from "@/api/IssueLine/IssueLine"
const { proxy } = getCurrentInstance()
const IssueLineList = ref([])
const loadingLine = ref(true)
const idsLine = ref([])
const singleLine = ref(true)
const multipleLine = ref(true)
const totalLine = ref(0)
const titleLine = ref("")

const dataLine = reactive({
  formtui: {},
  queryParamsLine: {
    pageNum: 1,
    pageSize: 10,
  },
  rulestui: {
    quantityIssued: [
      { required: true, message: "领料数量不能为空", trigger: "blur" }
    ],
    itemCode: [
      { required: true, message: "物料编码不能为空", trigger: "blur" }
    ]
  }
})

const { queryParamsLine, formtui, rulestui } = toRefs(dataLine)

/** 查询生产领料单行列表 */
function getListLine() {
  loadingLine.value = true
  listIssueLine(queryParamsLine.value).then(response => {
    IssueLineList.value = response.rows
    totalLine.value = response.total
    loadingLine.value = false
  })
}



// 表单重置
function resetLine() {
  formtui.value = {
    lineId: null,
    issueId: null,
    materialStockId: null,
    itemId: null,
    itemCode: null,
    itemName: null,
    specification: null,
    unitOfMeasure: null,
    quantityIssued: null,
    batchCode: null,
    warehouseId: null,
    warehouseCode: null,
    warehouseName: null,
    locationId: null,
    locationCode: null,
    locationName: null,
    areaId: null,
    areaCode: null,
    areaName: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("IssueLineRef")
}

// 多选框选中数据
function handleSelectionChangeLine(selection) {
  idsLine.value = selection.map(item => item.lineId)
  singleLine.value = selection.length != 1
  multipleLine.value = !selection.length
}

/** 新增按钮操作 */
function handleAddLine() {
  resetLine()
  open3.value = true
  titleLine.value = "添加生产领料单行"
}

const oldCount=ref()
/** 修改按钮操作 */
function handleUpdateLine(row) {
  oldCount.value=row.quantityIssued  
  resetLine()
  const _lineId = row.lineId || idsLine.value
  getIssueLine(_lineId).then(response => {
    formtui.value = response.data
    open3.value = true
    titleLine.value = "修改生产领料单行"
  })
}

/** 提交按钮 */
import {updataliang} from '@/api/line/line'
const newCount=ref()
const IssueLineRef=ref()
function submitFormLine() {
  //根据id修改仓库数量
  IssueLineRef.value.validate((valid) => {
    if (valid) {
      if (formtui.value.lineId != null) {
         newCount.value=oldCount.value-formtui.value.quantityIssued
        updataliang(formtui.value.materialStockId,newCount.value)
        updateIssueLine(formtui.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open3.value = false
          getListLine()
        })
      } else {
        updataliang(formtui.value.materialStockId,-formtui.value.quantityIssued)
        addIssueLine(formtui.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open3.value = false
          getListLine()
        })
      }
    }
  })
}
// 取消按钮
function cancelLine() {
  open3.value = false
  resetLine()
}
/** 删除按钮操作 */
function handleDeleteLine(row) {
  const _lineIds = row.lineId || idsLine.value
  proxy.$modal.confirm('是否确认删除生产领料单行编号为"' + _lineIds + '"的数据项？').then(function() {
    return delIssueLine(_lineIds)
  }).then(() => {
     updataliang(row.materialStockId,row.quantityIssued)//删除库存量增加
    getListLine(nowId.value)
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

getListLine()
//-------------------------------------生产领料单行表数据渲染结束
//-------------------------------------物料展示开始
// 物料
const open3 = ref(false)
const open4=ref(false)
//查看物料
 function kaii1() {
    open4.value=true
}
import { listStock} from "@/api/stock/stock"


const loading2 = ref(true)
const showSearch2 = ref(true)
const total2 = ref(0)

const data2 = reactive({
  formItem: {},
  queryParams2: {
    pageNum: 1,
    pageSize: 10,
    itemCode: null,
    itemName: null,
    itemTypeName: null,
     itemTypeId: 1,  // 新增：用于存储选中的物料分类ID
  },
})

const { queryParams2} = toRefs(data2)
const userList1 = ref([]);
/** 查询物料产品管理列表 */
function getList2() {
  loading2.value = true
  listStock(queryParams2.value).then(response => {
    userList1.value = response.rows
    total2.value = response.total
    loading2.value = false
  })
}



/** 搜索按钮操作 */
function handleQuery2() {
  queryParams2.value.pageNum = 1
  getList2()
}

/** 重置按钮操作 */
function resetQuery2() {
  proxy.resetForm("queryRef")
    // 清除分类ID查询条件
  queryParams2.value.itemTypeId = 1
  handleQuery2()
}
getList2()
const type1List = ref([])
const isExpandAll = ref(true)
const refreshTable = ref(true)
const data4 = reactive({
  queryParams4: {
  },
})

const { queryParams4 } = toRefs(data4)

/** 查询物料分类列表 */
function getList6() {
  loading2.value = true
  listType1(queryParams4.value).then(response => {
    type1List.value = proxy.handleTree(response.data, "itemTypeId", "parentTypeId")
    loading2.value = false
  })
}
getList6()


//下拉表
import { listType1} from "@/api/type1/type1"
//---------------------------------------------物料展示开始结束
//----------------------------------------------------物料选择开始
// 处理物料分类点击事件
function handleCategoryClick(row) {
  // 设置选中的分类ID到查询参数
  queryParams2.value.itemTypeId = row.itemTypeId
  // 重置页码为1
  queryParams2.value.pageNum = 1
  // 执行查询
  getList2()
}
const selectedUser = ref(null);
const userTableRef = ref(null); // 用于获取el-table实例
// 处理单选框变化事件
function handleRadioChange2(selection) {
  // 单选情况下，selection数组只会有0或1个元素
  selectedUser.value = selection.length > 0 ? selection[0] : null;
}

function handleTableRowClick(row) {
  console.log("点击的行对象：", row);
  selectedUser.value = row
  userTableRef.value.setCurrentRow(row)
}

// 确认选择按钮
function confirmSelectedItem2() {
  if (!selectedUser.value) {
    proxy.$modal.msgWarning("请选择一个物料");
    return;
  }
  console.log(selectedUser.value);
  // 将选中的物料信息回填到表单
  formtui.value.materialStockId = selectedUser.value.materialStockId;
  formtui.value.itemId = selectedUser.value.itemId;
  formtui.value.itemCode = selectedUser.value.itemCode;
  formtui.value.batchCode = selectedUser.value.batchCode;
  formtui.value.itemName = selectedUser.value.itemName;
  formtui.value.specification = selectedUser.value.specification;
  formtui.value.unitOfMeasure = selectedUser.value.unitOfMeasure;
  
  // 关闭物料选择框
  open4.value = false;
  selectedUser.value = null;
  if (userTableRef.value) {
    userTableRef.value.clearSelection();
  }
}

// 对话框关闭时的处理方法
const handleDialogClose1 = () => {
  open4.value = false;
  // 重置选中状态（关键：避免下次打开弹窗时保留上次选择）
  selectedUser.value = null;
  if (userTableRef.value) {
    userTableRef.value.clearSelection();
    userTableRef.value.setCurrentRow(null); // 取消行高亮
  }
};
const handleDialogClose3 = () => {
  open3.value = false; // 只关闭内层弹窗，不影响主表单
};
//--------------------------------------------物料选择结束


</script>
